package com.iad.controller.service
{
  import com.adobe.cairngorm.business.Responder;
  import com.iad.controller.event.*;
  import com.iad.model.*;
  import com.iad.model.valueobject.*;
  
  import flash.events.EventDispatcher;
  
  import mx.collections.ArrayCollection;
  import mx.controls.Alert;
  import mx.messaging.Channel;
  import mx.messaging.ChannelSet;
  import mx.messaging.channels.AMFChannel;
  import mx.rpc.AsyncToken;
  import mx.rpc.events.FaultEvent;
  import mx.rpc.events.ResultEvent;
  import mx.rpc.remoting.RemoteObject;
  
  public class SignupService extends EventDispatcher{
    private var responder:Responder;
    private var service:RemoteObject;
    [Bindable] private var model:ModelLocatorImpl = ModelLocatorImpl.getInstance();
    
    public static const SIGNUP_SERVICE:String = "signupService";
    
    public function SignupService() {    
      // initialize channel and remote object  
      var channelSet:ChannelSet = new ChannelSet();
      var myAMFChannel:Channel = new AMFChannel("signup-amf", "http://"+model.SERVER+":"+model.PORT+"/" + model.CONTEXT + "/messagebroker/amf");
      channelSet.addChannel(myAMFChannel);
      // here we still rely on remoting-config.xml (as pointed to by services-config.xml), specifying
      // the Java adapter and destination remote classes.  Perhaps we can find a way to define all of 
      // that here. 
    
      this.service = new RemoteObject();
      this.service.destination = SIGNUP_SERVICE;
      this.service.channelSet = channelSet;
      this.responder = responder;
    }
    
     public function sendWelcomeEmail(welcomeEmail:WelcomeEmail):void {
      var token:AsyncToken = service.sendWelcomeEmail(welcomeEmail);
      var responder:mx.rpc.Responder = new mx.rpc.Responder(sendWelcomeEmailOnResult, sendWelcomeEmailOnFault);
      token.addResponder(responder);
    }
    
    protected function sendWelcomeEmailOnResult(event:ResultEvent):void {
      dispatchEvent(new ServiceResultEvent(ServiceResultEvent.SEND_WELCOME_EMAIL_RESULT, event.result));
    }
    
    protected function sendWelcomeEmailOnFault(event:FaultEvent):void {
    }
    
    public function sendContactMessage(contactMessage:ContactMessage):void {
      var token:AsyncToken = service.sendContactMessage(contactMessage);
      var responder:mx.rpc.Responder = new mx.rpc.Responder(sendContactMessageOnResult, sendContactMessageOnFault);
      token.addResponder(responder);
    }
    
    protected function sendContactMessageOnResult(event:ResultEvent):void {
      dispatchEvent(new ServiceResultEvent(ServiceResultEvent.SEND_CONTACT_MESSAGE_RESULT, event.result));
    }
    
    protected function sendContactMessageOnFault(event:FaultEvent):void {
    }
    
    
  }
}